<?php
declare (strict_types=1);

namespace app\middleware;

use app\admin\service\business\Alone\Access\AccessMenuService;
use app\admin\service\business\Alone\Access\AccessService;
use app\admin\service\business\Alone\Token\TokenService;
use app\admin\service\business\controllers\Auth\AuthService;
use app\service\traits\Unified;

class CheckAuth
{
    use Unified;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response|object|\think\response\Redirect
     */
    public function handle($request, \Closure $next)
    {
        $tokenService = TokenService::getInstance();

        // 登录信息是否存在，是否有效
        $data = $tokenService->getValue($tokenService->get());
        if (!$data || !isset($data['id'])) return $this->response($request, 602, 'login');

        // 判断用户状态是否启用
        $user = AuthService::getInstance()->user($data['id']);
        if (!$user || !$user->status) {
            // 清除 token
            $tokenService->clear($tokenService->get());

            return $this->response($request, 603, 'login');
        }

        // 判断用户权限
        if (!$roles = AccessService::getInstance(['user' => $user])->boot()) return $this->response($request, 604, '404');

        return $next($request);
    }

    /**
     * 返回数据处理
     *
     * @param $request
     * @param int $code
     * @param string $url
     * @return object|\think\response\Redirect
     */
    private function response($request, int $code, string $url)
    {
        // 判断是否 ajax 请求
        if ($request->isAjax()) return $this->returnData($code);

        return redirect((string)url($url));
    }
}
